<template>
  <div class="mindmap-with-context-menu">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-group">
        <el-button 
          type="info" 
          size="small" 
          icon="el-icon-download" 
          @click="exportImage"
        >
          导出PNG
        </el-button>
        
        <el-button 
          type="warning" 
          size="small" 
          icon="el-icon-zoom-in" 
          @click="fitView"
        >
          适应画布
        </el-button>
      </div>
    </div>
    
    <!-- 思维导图容器 -->
    <div 
      class="mindmap-container" 
      ref="mindMapContainer"
      @contextmenu.prevent="handleCanvasContextMenu"
    ></div>
    
    <!-- 右键菜单组件 -->
    <ContextMenu 
      ref="contextMenu" 
      @menu-click="handleContextMenuClick"
      @show="onContextMenuShow"
      @hide="onContextMenuHide"
    />
    
    <!-- 运输线路管理对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleDialogClose"
    >
      <div class="dialog-content">
        
        <!-- 根据不同操作类型显示不同内容 -->
        <div v-if="showActionForm" class="action-form">
          <el-form :model="actionForm" label-width="120px">
            <el-form-item 
              v-if="currentAction.type === 'addTransportPoint'" 
              label="点位名称"
            >
              <el-input 
                v-model="actionForm.pointName" 
                placeholder="请输入运输点位名称"
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item 
              v-if="currentAction.type === 'modifyRoute'" 
              label="线路名称"
            >
              <el-input 
                v-model="actionForm.routeName" 
                placeholder="请输入线路名称"
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item 
              v-if="currentAction.type === 'editNodeText'" 
              label="节点内容"
            >
              <el-input 
                v-model="actionForm.nodeText" 
                placeholder="请输入节点内容"
                clearable
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmAction" 
          :loading="actionLoading"
        >
          确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MindMap from "simple-mind-map";
import ContextMenu from './ContextMenu.vue';

// 导入插件
import Export from 'simple-mind-map/src/plugins/Export.js';
import Drag from 'simple-mind-map/src/plugins/Drag.js';

// 注册插件
MindMap.usePlugin(Export);
MindMap.usePlugin(Drag);

export default {
  name: 'MindMapWithContextMenu',
  components: {
    ContextMenu
  },
  
  data() {
    return {
      mindMap: null,
      hasActiveNode: false,
      contextMenuTarget: null,
      allowEdit: false, // 控制是否允许编辑的标志位
      
      // 对话框相关状态
      dialogVisible: false,
      dialogTitle: '',
      dialogMessage: '',
      currentAction: null,
      showActionForm: false,
      actionLoading: false,
      
      // 表单数据
      actionForm: {
        pointName: '',
        routeName: '',
        remark: '',
        nodeText: '' // 节点编辑文本
      },
      
      // 思维导图初始数据
      initialData: {
        "data": {
          "text": "右键菜单思维导图",
          "expand": true,
          "isActive": true
        },
        "children": [
          {
            "data": {
              "text": "右键功能",
              "expand": true
            },
            "children": [
              {
                "data": {
                  "text": "节点操作",
                  "expand": true
                },
                "children": []
              },
              {
                "data": {
                  "text": "样式设置",
                  "expand": true
                },
                "children": []
              }
            ]
          },
          {
            "data": {
              "text": "快捷键支持",
              "expand": true
            },
            "children": [
              {
                "data": {
                  "text": "Tab - 添加子节点",
                  "expand": true
                },
                "children": []
              },
              {
                "data": {
                  "text": "Enter - 添加同级节点",
                  "expand": true
                },
                "children": []
              },
              {
                "data": {
                  "text": "Delete - 删除节点",
                  "expand": true
                },
                "children": []
              }
            ]
          }
        ]
      }
    }
  },
  
  mounted() {
    this.initMindMap();
  },
  
  beforeDestroy() {
    if (this.mindMap) {
      // 不恢复快捷键，保持禁用状态
      // this.mindMap.keyCommand.recovery();
      this.mindMap.destroy();
    }
  },
  
  methods: {
    /**
     * 初始化思维导图
     */
    initMindMap() {
      this.mindMap = new MindMap({
        el: this.$refs.mindMapContainer,
        data: this.initialData,
        layout: 'logicalStructure',
        theme: 'default',
        // 禁用所有快捷键
        customCheckEnableShortcut: () => false,
        // 禁用鼠标在SVG外面时的快捷键
        enableShortcutOnlyWhenMouseInSvg: false,
        // 尝试隐藏节点展开按钮
        showExpandBtn: false
      });
      
      this.bindEvents();
      
      // 暂停所有快捷键响应
      this.mindMap.keyCommand.pause();
      
      // 移除所有默认快捷键
      this.removeAllShortcuts();
      
      // 禁用默认的双击编辑行为
      this.disableDefaultEdit();
    },
    
    /**
     * 禁用默认的节点编辑行为
     */
    disableDefaultEdit() {
      // 保存原始的textEdit.show方法
      const originalShow = this.mindMap.renderer.textEdit.show.bind(this.mindMap.renderer.textEdit);
      
      // 标志位，标识是否允许编辑
      this.allowEdit = false;
      
      // 重写textEdit.show方法
      this.mindMap.renderer.textEdit.show = (options) => {
        if (this.allowEdit) {
          // 允许编辑时调用原始方法
          this.allowEdit = false; // 重置标志位
          return originalShow(options);
        } else {
          // 不允许编辑时阻止
          console.log('节点编辑被禁用，请使用右键菜单编辑');
          return;
        }
      };
      
      // 监听双击事件，显示编辑弹窗
      this.mindMap.on('node_dblclick', (node, e) => {
        e.preventDefault();
        e.stopPropagation();
        // 双击显示编辑弹窗
        this.showEditNodeDialog(node);
        console.log('双击节点，显示编辑弹窗:', node.nodeData.data.text);
      });
    },
    
    /**
     * 开始节点编辑（仅可通过右键菜单调用）
     */
    startNodeEdit(node) {
      // 激活节点
      node.active();
      
      // 设置允许编辑标志
      this.allowEdit = true;
      
      // 手动启动节点编辑
      this.mindMap.renderer.textEdit.show({
        node: node
      });
      
      console.log('开始编辑节点:', node.nodeData.data.text);
    },
    
    /**
     * 显示节点编辑弹窗（双击触发）
     */
    showEditNodeDialog(node) {
      // 设置当前操作为编辑节点
      this.currentAction = {
        type: 'editNodeText',
        node: node
      };
      
      // 设置弹窗标题和显示表单
      this.dialogTitle = '编辑节点内容';
      this.showActionForm = true;
      
      // 设置表单初始值
      this.actionForm.nodeText = node.nodeData.data.text || '';
      
      // 显示弹窗
      this.dialogVisible = true;
      
      console.log('显示节点编辑弹窗:', node.nodeData.data.text);
    },
    
    /**
     * 移除所有默认快捷键
     */
    removeAllShortcuts() {
      const defaultShortcuts = [
        'Tab',
        'Enter', 
        'Shift+Tab',
        'Ctrl+↑',
        'Ctrl+↓',
        'Ctrl+G',
        '/',
        'Delete',
        'Backspace',
        'Shift+Backspace',
        'Ctrl+C',
        'Ctrl+X',
        'Ctrl+V',
        'F2',
        'Shift+Enter',
        'Ctrl+Z',
        'Ctrl+Y',
        'Ctrl+A',
        'Ctrl+L',
        'Ctrl++',
        'Ctrl+-',
        'Ctrl+Enter',
        'Ctrl+i'
      ];
      
      defaultShortcuts.forEach(key => {
        try {
          this.mindMap.keyCommand.removeShortcut(key);
        } catch (e) {
          // 忽略错误，继续移除其他快捷键
        }
      });
    },
    
    /**
     * 绑定事件监听
     */
    bindEvents() {
      // 监听节点激活状态
      this.mindMap.on('node_active', (node, activeNodeList) => {
        this.hasActiveNode = activeNodeList.length > 0;
      });
      
      // 监听节点右键菜单事件
      this.mindMap.on('node_contextmenu', (e, node) => {
        this.handleNodeContextMenu(e, node);
      });
      
      // 监听画布右键菜单事件
      this.mindMap.on('contextmenu', (e) => {
        this.handleCanvasContextMenu(e);
      });
      
      // 监听节点点击
      this.mindMap.on('node_click', (node, e) => {
        console.log('节点点击:', node);
      });
      
      // 监听数据变化
      this.mindMap.on('data_change', (data) => {
        console.log('数据变化:', data);
      });
    },
    
    /**
     * 处理节点右键菜单
     */
    handleNodeContextMenu(event, node) {
      const menuItems = this.getNodeContextMenuItems(node);
      this.contextMenuTarget = { type: 'node', node };
      this.$refs.contextMenu.show(event, menuItems, this.contextMenuTarget);
    },
    
    /**
     * 处理画布右键菜单
     */
    handleCanvasContextMenu(event) {
      const menuItems = this.getCanvasContextMenuItems();
      this.contextMenuTarget = { type: 'canvas', position: { x: event.clientX, y: event.clientY } };
      this.$refs.contextMenu.show(event, menuItems, this.contextMenuTarget);
    },
    
    /**
     * 获取节点右键菜单项
     */
    getNodeContextMenuItems(node) {
      // 添加编辑节点到右键菜单
      return [
        {
          label: '编辑节点',
          icon: 'icon-edit',
          handler: () => this.startNodeEdit(node)
        },
        {
          type: 'separator'
        },
        {
          label: '添加运输点位',
          icon: 'icon-location',
          handler: () => this.handleTransportAction('addTransportPoint', node)
        },
        {
          label: '查看线路地图',
          icon: 'icon-map',
          handler: () => this.handleTransportAction('viewRouteMap', node)
        },
        {
          label: '修改线路',
          icon: 'icon-edit-route',
          handler: () => this.handleTransportAction('modifyRoute', node)
        },
        {
          type: 'separator'
        },
        {
          label: '提交线路',
          icon: 'icon-submit',
          handler: () => this.handleTransportAction('submitRoute', node)
        },
        {
          label: '撤回线路',
          icon: 'icon-recall',
          handler: () => this.handleTransportAction('recallRoute', node)
        }
      ];
    },
    
    /**
     * 获取画布右键菜单项
     */
    getCanvasContextMenuItems() {
      return [
        {
          label: '添加根节点',
          icon: 'icon-add-root',
          handler: () => this.addRootNode()
        },
        {
          type: 'separator'
        },
        {
          label: '全选',
          icon: 'icon-select-all',
          handler: () => this.selectAllNodes()
        },
        {
          label: '取消选择',
          icon: 'icon-deselect',
          handler: () => this.deselectAllNodes()
        },
        {
          type: 'separator'
        },
        {
          label: '适应画布',
          icon: 'icon-fit',
          handler: () => this.fitView()
        },
        {
          label: '重置视图',
          icon: 'icon-reset',
          handler: () => this.resetView()
        },
        {
          type: 'separator'
        },
        {
          label: '导出',
          icon: 'icon-export',
          children: [
            {
              label: '导出PNG',
              icon: 'icon-image',
              handler: () => this.exportImage()
            },
            {
              label: '导出SVG',
              icon: 'icon-vector',
              handler: () => this.exportSVG()
            },
            {
              label: '导出JSON',
              icon: 'icon-data',
              handler: () => this.exportJSON()
            }
          ]
        }
      ];
    },
    
    /**
     * 右键菜单点击处理
     */
    handleContextMenuClick({ item, target }) {
      console.log('右键菜单点击:', item.label, target);
    },
    
    /**
     * 右键菜单显示时的处理
     */
    onContextMenuShow({ event, items, target }) {
      console.log('右键菜单显示', target);
    },
    
    /**
     * 右键菜单隐藏时的处理
     */
    onContextMenuHide() {
      this.contextMenuTarget = null;
    },
    
    // ========== 运输线路管理方法 ==========
    
    /**
     * 处理运输相关操作
     */
    handleTransportAction(actionType, node) {
      const actionConfig = {
        'addTransportPoint': {
          title: '添加运输点位',
          message: '您点击了“添加运输点位”功能',
          showForm: true
        },
        'viewRouteMap': {
          title: '查看线路地图',
          message: '您点击了“查看线路地图”功能',
          showForm: false
        },
        'modifyRoute': {
          title: '修改线路',
          message: '您点击了“修改线路”功能',
          showForm: true
        },
        'submitRoute': {
          title: '提交线路',
          message: '您点击了“提交线路”功能',
          showForm: true
        },
        'recallRoute': {
          title: '撤回线路',
          message: '您点击了“撤回线路”功能',
          showForm: true
        },
        'deleteRoute': {
          title: '删除线路',
          message: '您点击了“删除线路”功能，此操作不可恢复！',
          showForm: false
        }
      };
      
      const config = actionConfig[actionType];
      if (!config) {
        console.warn('未知的操作类型:', actionType);
        return;
      }
      
      this.currentAction = {
        type: actionType,
        label: config.title,
        target: { type: 'node', node },
        timestamp: new Date().toLocaleString()
      };
      
      this.dialogTitle = config.title;
      this.dialogMessage = config.message;
      this.showActionForm = config.showForm;
      this.dialogVisible = true;
      
      // 重置表单数据
      this.resetActionForm();
    },
    
    /**
     * 重置表单数据
     */
    resetActionForm() {
      this.actionForm = {
        pointName: '',
        routeName: '',
        remark: '',
        nodeText: ''
      };
    },
    
    /**
     * 关闭对话框
     */
    handleDialogClose() {
      this.dialogVisible = false;
      this.currentAction = null;
      this.showActionForm = false;
      this.actionLoading = false;
      this.resetActionForm();
    },
    
    /**
     * 确认操作
     */
    async confirmAction() {
      if (!this.currentAction) return;
      
      this.actionLoading = true;
      
      try {
        // 模拟异步操作
        await this.performTransportAction(this.currentAction.type);
        
        this.$message.success(`${this.currentAction.label}操作成功！`);
        this.handleDialogClose();
        
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error(`${this.currentAction.label}操作失败！`);
      } finally {
        this.actionLoading = false;
      }
    },
    
    /**
     * 执行运输相关操作
     */
    async performTransportAction(actionType) {
      // 模拟异步操作延时
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const node = this.currentAction.target ? this.currentAction.target.node : this.currentAction.node;
      
      switch (actionType) {
        case 'editNodeText':
          if (!this.actionForm.nodeText.trim()) {
            throw new Error('请输入节点内容');
          }
          
          console.log('编辑节点文本:', {
            oldText: node.nodeData.data.text,
            newText: this.actionForm.nodeText.trim()
          });
          
          // 更新节点文本
          node.nodeData.data.text = this.actionForm.nodeText.trim();
          
          // 重新渲染思维导图
          this.mindMap.render();
          
          break;
          
        case 'addTransportPoint':
          if (!this.actionForm.pointName.trim()) {
            throw new Error('请输入点位名称');
          }
          
          console.log('添加运输点位:', {
            nodeName: node.nodeData.data.text,
            pointName: this.actionForm.pointName
          });
          
          // 激活当前节点
          node.active();
          
          // 在当前节点下添加子节点
          this.mindMap.execCommand('INSERT_CHILD_NODE', false, [], {
            text: this.actionForm.pointName.trim()
          });
          
          break;
          
        case 'viewRouteMap':
          console.log('查看线路地图:', {
            nodeName: node.nodeData.data.text
          });
          // 这里可以打开地图窗口或跳转到地图页面
          break;
          
        case 'modifyRoute':
          if (!this.actionForm.routeName.trim()) {
            throw new Error('请输入线路名称');
          }
          console.log('修改线路:', {
            nodeName: node.nodeData.data.text,
            routeName: this.actionForm.routeName
          });
          break;
          
        case 'submitRoute':
          console.log('提交线路:', {
            nodeName: node.nodeData.data.text,
            remark: this.actionForm.remark
          });
          break;
          
        case 'recallRoute':
          console.log('撤回线路:', {
            nodeName: node.nodeData.data.text,
            remark: this.actionForm.remark
          });
          break;
          
        case 'deleteRoute':
          console.log('删除线路:', {
            nodeName: node.nodeData.data.text
          });
          break;
          
        default:
          throw new Error('未知的操作类型');
      }
    },
    
    /**
     * 适应画布
     */
    fitView() {
      this.mindMap.view.fit();
    },
    
    /**
     * 添加根节点（示例，实际可能需要特殊处理）
     */
    addRootNode() {
      console.log('添加根节点功能暂未实现');
    },
    
    /**
     * 全选所有节点
     */
    selectAllNodes() {
      this.mindMap.execCommand('SELECT_ALL');
    },
    
    /**
     * 取消选择所有节点
     */
    deselectAllNodes() {
      this.mindMap.renderer.clearActiveNodeList();
    },
    
    /**
     * 重置视图
     */
    resetView() {
      this.mindMap.view.reset();
    },
    
    /**
     * 导出图片
     */
    exportImage() {
      this.mindMap.export('png', true, '思维导图').then(url => {
        const a = document.createElement('a');
        a.href = url;
        a.download = '思维导图.png';
        a.click();
      });
    },
    
    /**
     * 导出SVG
     */
    exportSVG() {
      this.mindMap.export('svg', true, '思维导图').then(url => {
        const a = document.createElement('a');
        a.href = url;
        a.download = '思维导图.svg';
        a.click();
      });
    },
    
    /**
     * 导出JSON
     */
    exportJSON() {
      const data = this.mindMap.getData();
      const jsonStr = JSON.stringify(data, null, 2);
      const blob = new Blob([jsonStr], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '思维导图.json';
      a.click();
      URL.revokeObjectURL(url);
    }
  }
}
</script>

<style scoped>
.mindmap-with-context-menu {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.toolbar {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  gap: 15px;
  flex-wrap: wrap;
}

.toolbar-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-group .el-button {
  margin-left: 0;
  margin-right: 8px;
}

.toolbar-group .el-button:last-child {
  margin-right: 0;
}

.mindmap-container {
  flex: 1;
  background-color: #fafafa;
  position: relative;
}

/* 对话框样式 */
.dialog-content {
  padding: 10px 0;
}

.action-details {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.action-details p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

.action-details strong {
  color: #303133;
}

.action-form {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 8px;
}

/* 运输线路相关图标 */
.icon-transport::before { content: '🚛'; }
.icon-location::before { content: '📍'; }
.icon-map::before { content: '🗺️'; }
.icon-edit-route::before { content: '✏️'; }
.icon-submit::before { content: '📤'; }
.icon-recall::before { content: '↩️'; }
.icon-delete-route::before { content: '🗑️'; }

/* 原有图标样式保持不变 */
.icon-add-child::before { content: '📁'; }
.icon-add-sibling::before { content: '📄'; }
.icon-delete::before { content: '🗑️'; }
.icon-export::before { content: '💾'; }
.icon-fit::before { content: '🔍'; }
.icon-edit::before { content: '✏️'; }
.icon-style::before { content: '🎨'; }
.icon-bold::before { content: '𝐁'; }
.icon-italic::before { content: '𝐼'; }
.icon-underline::before { content: '𝐔'; }
.icon-color::before { content: '🌈'; }
.icon-copy::before { content: '📋'; }
.icon-paste::before { content: '📌'; }
.icon-add-root::before { content: '🌳'; }
.icon-select-all::before { content: '🔲'; }
.icon-deselect::before { content: '❌'; }
.icon-reset::before { content: '🔄'; }
.icon-image::before { content: '🖼️'; }
.icon-vector::before { content: '📐'; }
.icon-data::before { content: '📊'; }

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar-group {
    justify-content: center;
  }
}

:deep(.smm-quick-create-child-btn){
  display: none;
}
</style>
